package com.nbsaas.lbs.qq.v1.service;

import com.google.gson.Gson;
import com.nbsaas.http.Connection;
import com.nbsaas.http.HttpConnection;
import com.nbsaas.lbs.qq.v1.domain.request.SearchByCityRequest;
import com.nbsaas.lbs.qq.v1.domain.request.SearchByNearbyRequest;
import com.nbsaas.lbs.qq.v1.domain.response.Pois;

import java.io.IOException;

public class PlaceService extends BaseService {
  
  
  
  public PlaceService(String key) {
    super(key);
  }
  
  public Pois searchByCity(SearchByCityRequest request) {
    Connection connection = HttpConnection.connect("https://apis.map.qq.com/ws/place/v1/search");
    connection.data("key", key);
    connection.data("keyword", request.getKeyword());
    connection.data("output", "json");
    connection.data("boundary", "region(" + request.getCity() + ",0)");
    connection.data("page_size", "" + request.getSize());
    connection.data("page_index", "" + request.getNo());
    connection.data("orderby", "" + request.getOrderby());
    connection.method(Connection.Method.GET);
    return getPois(connection);
  }
  
  private Pois getPois(Connection connection) {
    Pois result = new Pois();
    try {
      String body = connection.execute().body();
      System.out.println(body);
      Gson gson = new Gson();
      result = gson.fromJson(body, Pois.class);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
  
  public Pois searchByNearby(SearchByNearbyRequest request) {
    Connection connection = HttpConnection.connect("https://apis.map.qq.com/ws/place/v1/search");
    connection.data("key", key);
    connection.data("keyword", request.getKeyword());
    connection.data("output", "json");
    connection.data("boundary", "nearby(" + request.getLat()+","+request.getLng() + ","+request.getRadius()+")");
    connection.data("page_size", "" + request.getSize());
    connection.data("page_index", "" + request.getNo());
    connection.data("orderby", "" + request.getOrderby());
    connection.method(Connection.Method.GET);
    return getPois(connection);
  }
  
  
  protected Connection getConnection(String url) {
    Connection connection = HttpConnection.connect(url);
    return connection;
  }
  
  public static void main(String[] args) {
    PlaceService service = new PlaceService("H4DBZ-WLVCU-YLEVF-4MIDF-MGB5H-TOFDR");
    SearchByNearbyRequest request = new SearchByNearbyRequest();
    request.setKeyword("酒店");
    request.setLat(29.42444f);
    request.setLng(106.26241f);
    request.setRadius(1000);
    Pois pois = service.searchByNearby(request);
    System.out.println(pois);
  }
  
  private static void s() {
    PlaceService service = new PlaceService("H4DBZ-WLVCU-YLEVF-4MIDF-MGB5H-TOFDR");
    SearchByCityRequest request = new SearchByCityRequest();
    request.setKeyword("重庆恒大酒店");
    request.setCity("重庆");
    Pois pois = service.searchByCity(request);
    System.out.println(pois);
  }
}
